# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         testsuite2testcase.py
# Description:  
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019/11/26 9:16
# -------------------------------------------------------------------------------
from django.db import transaction
from rest_framework import status
from rest_framework.mixins import CreateModelMixin, ListModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from apps.HttpAutoTestService.core.builtin.functions import get_timestamp
from apps.HttpAutoTestService.filters import Testsuite2TestcaseFilter
from apps.HttpAutoTestService.models import Testsuite2Testcase, Testcase
from apps.HttpAutoTestService.serializers import Testsuite2TestcaseSerializer

__all__ = ['Testsuite2TestcaseViewSet', ]


class Testsuite2TestcaseViewSet(CreateModelMixin, ListModelMixin, GenericViewSet):
    queryset = Testsuite2Testcase.objects.filter()
    serializer_class = Testsuite2TestcaseSerializer
    filter_class = Testsuite2TestcaseFilter
    pagination_class = None

    @transaction.atomic
    def create(self, request, *args, **kwargs):
        testsuite2testcase = request.data
        testsuite_id = testsuite2testcase.get('testsuite_id') if testsuite2testcase else None
        data = testsuite2testcase.get('data') if testsuite2testcase else None

        Testsuite2Testcase.objects.filter(testsuite_id=testsuite_id).delete()
        testsuite2testcase = []
        for item in data:
            if item.get('update_testcase', False):
                # 与更新测试用例的 情况二 相对应，修改时要一并修改（代码开始）
                testcase_id = item.get('testcase_id')
                testcase_name = item.get('testcase_name')
                if testcase_name and Testcase.objects.filter(name=testcase_name) and not Testcase.objects.filter(
                        id=testcase_id, name=testcase_name):
                    # 用例名称在数据库中已经存在，生成一个新用例名称
                    testcase_name = '{testcase_name}-{timestamp}'.format(testcase_name=testcase_name,
                                                                         timestamp=str(get_timestamp(16))[10:])
                    item['testcase_name'] = testcase_name
                url = item.get('url')
                request_params = item.get('request_params')
                headers = item.get('headers')
                request_data_type = item.get('request_data_type')
                request_data = item.get('request_data')
                expect_result = item.get('expect_result')
                testcase = {
                    'name': testcase_name,
                    'url': url,
                    'headers': headers,
                    'request_params': request_params,
                    'request_data_type': request_data_type,
                    'request_data': request_data,
                    'expect_result': expect_result,
                }
                Testcase.objects.filter(id=testcase_id).update(**testcase)
                # 与更新测试用例的 情况二 相对应（代码结束）
                del item['update_testcase']
            testsuite2testcase.append(Testsuite2Testcase(**item))
        Testsuite2Testcase.objects.bulk_create(testsuite2testcase)
        return Response(status=status.HTTP_201_CREATED, content_type='application/json')
